<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="keywords" content="井字棋,小游戏">
    <meta name="description" content="本页面是井字棋小游戏-大小棋子模式">
    <title>激情对抡-大小棋模式</title>
    <div th:replace="tools/_fragments-tools::basicrefrence"></div>
    <style>
        .ui.segment.scrolling.always-scroll {
            overflow-y: scroll;
        }
    </style>
</head>

<body class="unselect">

<nav th:replace="tools/_fragments-tools::head"></nav>

<div class="ui teal message" style="display: none;z-index:9999;float: left; position: relative;left: 50%;margin-left: -50px;">这是一个自动消失的提示框</div>

<div class="m-tenDistance" style="height: 80%">
    <div class="ui container" style="height: 100%">
        <div class="ui stackable grid" style="height: 100%">
            <!-- 左侧选择栏 -->
            <div class="eight wide column">
                <div class="ui center aligned mobile stackable segment">
                    <div class="ui container">
                        <div class="ui middle aligned center aligned mobile stackable grid">
                            <div class="six wide column">

                                <h1 class="ui teal image header">
                                    <img id="startButton" onclick="ready()" src="/images/ticTacToe/startButton.gif" class="image" draggable="false">
                                </h1>

                                <form class="ui large form" method="post" action="#">
                                    <div id="mapSegment" class="ui stacked segment">

                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <button id="copyButton" class="mini ui inverted secondary button">分享房间链接</button>
            </div>

            <!-- 右侧对话框 -->
            <div class="eight wide column" style="height: 100%">
                <div class="ui attached segment scrolling always-scroll content" id="dialogDiv" style="height: 90%">
                </div>
                <div class="ui bottom attached segment" >
                    <div id="diagueDiv" class="ui input" style="width: 60%">
                        <input type="text" placeholder="狠狠羞辱你的对手吧" id="diague">
                    </div>
                    <button class="ui primary button" id="query-btn" onclick="submitDiague()">
                        发送
                    </button>
                </div>
            </div>
        </div>

    </div>
</div>


</body>

<img src="/images/ticTacToe/0.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/1.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/2.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/10.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/10-.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/12.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/12-.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/20.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/20-.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/21.png" className="image" draggable="false" style="visibility: hidden">
<img src="/images/ticTacToe/21-.png" className="image" draggable="false" style="visibility: hidden">

<script>

    function getFirstQueryParam() {
        var urlParams = new URLSearchParams(window.location.search);
        for (let param of urlParams.entries()) {
            return param[1]; // 返回第一个参数的名称
            // 如果你想要返回第一个参数的值，可以改为 return param[1];
        }
        return null; // 如果没有参数，则返回null
    }

    let room = null;
    let me = null;
    let mapSegment = $('#mapSegment');
    var websocket = null;
    var websocketPage = null;

    let diagueDiv = $('#dialogDiv');

    let roomId = getFirstQueryParam();
    if (roomId == null) {
        $.ajax({
            url:"createRoom",
            type:"POST",
            data:{
                roomType : 1
            },
            success:function (data) {
                room = data.data;
                me = room.gamers[0];
                createSocket();
                displayBoard(room.board);
            }
        })
    }
    else {
        $.ajax({
            url:"joinRoom",
            type:"POST",
            data:{
                roomId : roomId
            },
            success:function (data) {
                if (data.code === 0) {
                    messageDisplay(data.msg);
                    return;
                }
                room = data.data;
                me = room.gamers[1];
                createSocket();
                displayBoard(room.board);

            }
        })
    }

    function doIt(site,size) {
        if (room.state !== 0) {
            return;
        }
        if (me.type === 0) {
            messageDisplay("对方的回合");
            return;
        }

        let x = Math.floor(site / 10);
        let y = Math.floor(site % 10);
        let originalData = room.board[x][y];

        if ((size === 1 && originalData !== 0)
            || (size === 10 && (Math.floor(originalData / 10) !== 0) || originalData % 10 === me.power)) {
            messageDisplay("不能下在这里");
            return;
        }
        $.ajax({
            url: "doIt",
            type: "POST",
            data: {
                roomId:room.id,
                site: site,
                id: me.id,
                size: size
            },
            success: function (data) {
                if (data.code === 0) {
                    messageDisplay(data.msg);
                }
            },
        })
    }


    function ready() {
        if (me.state === 0) {
            $.ajax({
                url: "ready",
                type: "POST",
                data: {
                    roomId: room.id,
                    id: me.id
                },
                success: function (data) {
                },
            })
        }else {
            messageDisplay("您已经准备");
        }
    }


    function displayBoard(board) {
        let big = [
            [0,0,0],
            [0,0,0],
            [0,0,0]
        ];
        if (room.gamers[0] != null && room.gamers[0] !== undefined
        && room.gamers[0].big[2][0] !== -1 && room.gamers[0].big[2][1] !== -1){

            big[room.gamers[0].big[2][0]][room.gamers[0].big[2][1]] = 1;
        }
        if (room.gamers[1] != null && room.gamers[1] !== undefined
        && room.gamers[1].big[2][0] !== -1 && room.gamers[1].big[2][1] !== -1){
            big[room.gamers[1].big[2][0]][room.gamers[1].big[2][1]] = 1;
        }
        var visualMap = "";
        $('.chess').off('mousedown');
        for (var i = 0; i < 3; ++i) {
            visualMap += "<div className=\"field\">";
            for (var j = 0; j < 3; ++j) {
                let sTemp = "";
                if (big[i][j] === 1) {
                    sTemp = "-";
                }
                visualMap +=
                    "<img class='chess' src=\"/images/ticTacToe/" +
                    board[i][j] + sTemp +
                    ".png\" className=\"image\" data-site='"+i + j + "' draggable=\"false\" wide='35px' height='35px' style=\"border: solid;margin-left: 2px\">";
            }
            visualMap += "</div>";
        }
        mapSegment.html(visualMap);

        $('.chess').on('mousedown', function(e) {
            let thisSite = $(this).data('site');
            if (e.button === 0) {
                doIt(thisSite,1);
            } else if (e.button === 2) {

                doIt(thisSite,10);
                return false;
            }
        });
    }

    function createSocket(){
        $.ajax({
            url:"getSocketUrl",
            type:"GET",
            success:function (data) {
                if (data.code === 0){
                    messageDisplay(data.msg);
                    return;
                }
                if('websocket' in window){
                    let url = data.data + me.id;
                    websocketPage = new WebSocket(url);
                }else{
                    alert('浏览器不支持，请尝试更换浏览器，尝试更换后失败请联系管理员');
                }
                //建立websocket时自动调用
                websocketPage.onopen = function (event) {
                }
                //关闭webscoket时自动调用
                websocketPage.oncolse = function (event){
                    alert("连接即将关闭，如果您不想关闭对话连接，请刷新页面重新连接到服务器");
                }
                //websocket接收到消息时调用
                websocketPage.onmessage = function (event){
                    let dataObj= JSON.parse(event.data);
                    if (dataObj.code !== 2) {
                        otherSpeak(dataObj.data);
                        return
                    }
                    room = dataObj.data;
                    room.gamers.forEach(g =>{
                        if (g.id === me.id) {
                            me = g;
                        }
                    });
                    displayBoard(room.board);
                    if (me.type === 1) {
                        messageDisplay("你的回合");
                    }
                    console.log(room.state);
                    if (room.state === me.power) {
                        alert("你赢了");
                    }else if (room.state > 0) {
                        alert("你输了");
                    }
                }
                //websocket出错自动调用
                websocketPage.onerror = function () {
                    alert('websocket出错');
                }
                //关闭窗口前关闭websocket连接
                window.onbeforeunload = function (){
                    websocketPage.close();
                }
            }
        })
    }


    function submitDiague() {
        let diague = $('#diague').val();
        $('#diague').val("");
        if (diague == null || diague.length === 0) {
            return;
        }
        meSpeak(diague);
        $.ajax({
            url: "submitDiague",
            type: "POST",
            data: {
                roomId: room.id,
                id: me.id,
                diague: diague
            },
            success: function (data) {

            }
        })
    }


    function meSpeak(diague) {
        addDialog("me.jpg","我",diague);
    }

    function otherSpeak(diague) {
        addDialog("other.png","对方",diague);
    }

    function addDialog(avatar, who, dialog) {
        diagueDiv.append("<div class=\"ui segment\">\n" +
            "                    <span>\n" +
            "                    <a class=\"avatar\">\n" +
            "                        <img src=\"/images/ticTacToe/" + avatar + "\" style=\"height: 30px; width: 30px\">\n" +
            "                    </a>\n" +
            "                </span>\n" +
            "                    <span class=\"content\">\n" +
            "                    <a class=\"author\">" + who + "</a>\n" +
            "                </span>\n" +
            "                    <div>\n" +
            "                        " + dialog + "\n" +
            "                    </div>\n" +
            "                </div>");
        diagueDiv.scrollTop(diagueDiv.prop('scrollHeight'));
    }

    // 一键复制
    var copyButton = $('#copyButton');
    copyButton.on('click', function() {
        let str = window.location.href + "?roomId=" + room.id;
        let input = document.createElement("input");
        let body = document.querySelector("body");
        body.append(input);
        input.value = str
        input.select();
        document.execCommand("copy");
        input.remove();
    })

    /**
     * 禁止右键菜单
     * @returns {boolean}
     */
    document.oncontextmenu = function () {
        return false;
    }

    function messageDisplay(content) {
        // 显示并自动隐藏 Message 组件
        $('.ui.message')
            .text(content)
            .fadeIn('slow')
            .delay(1000)  // 设置显示时间，单位是毫秒
            .fadeOut('slow', function() {
                // 隐藏后移除 Message 组件
                $(this).css("display","none");
            });
    }

</script>
</html>